package com.example.library.service;

import com.example.library.entity.User;
import com.example.library.repository.BorrowRecordRepository;
import com.example.library.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ReaderService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BorrowRecordRepository borrowRecordRepository;
    public List<User> findAllReaders() {
        return userRepository.findAll().stream().filter(u -> "reader".equals(u.getRole())).toList();
    }
    public User save(User user) {
        if (user.getId() != null) {
            // 编辑时如未填写密码则保留原密码
            User old = userRepository.findById(user.getId()).orElse(null);
            if (old != null && (user.getPassword() == null || user.getPassword().isEmpty())) {
                user.setPassword(old.getPassword());
            }
        }
        return userRepository.save(user);
    }
    public void deleteById(Integer id) {
        // 删除前先检查是否有借阅记录
        if (borrowRecordRepository.count() > 0) {
            long count = borrowRecordRepository.findAll().stream().filter(r -> r.getUser() != null && id.equals(r.getUser().getId())).count();
            if (count > 0) {
                throw new RuntimeException("该读者有借阅记录，无法删除");
            }
        }
        userRepository.deleteById(id);
    }
}
